package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnLikesBehaviorServiceImpl extends ServiceImpl<ApUnLikesBehaviorMapper, ApUnlikesBehavior> implements ApUnLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    /**
     * 存储不喜欢数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        if (dto==null || dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //******************查找行为实体*****************
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry behaviorEntry=null;
        //已登录时
        if (user!=null && user.getId()!=null){
            behaviorEntry = apBehaviorEntryService
                    .findByUserIdOrEquipmentId(user.getId(), null);
        }
        //未登录
        behaviorEntry = apBehaviorEntryService
                .findByUserIdOrEquipmentId(null, 0);
        if (behaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查找不喜欢行为，有值时更新，无值时新增
        ApUnlikesBehavior unlikesBehavior = getOne(
                Wrappers.<ApUnlikesBehavior>lambdaQuery()
                        .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                        .eq(ApUnlikesBehavior::getEntryId, behaviorEntry.getId())
        );
        //也可以设计无需重复不喜欢，已经是取消状态*********************边界条件设计************此处不想写
        if (unlikesBehavior==null){
            //插入数据 save
            unlikesBehavior= ApUnlikesBehavior.builder()
                    .entryId(behaviorEntry.getId())
                    .articleId(dto.getArticleId())
                    .type(dto.getType())
                    .createdTime(new Date())
                    .build();
            save(unlikesBehavior);
        }else {
            //更新type  喜欢与不喜欢即可 update
            unlikesBehavior.setType(dto.getType());
            updateById(unlikesBehavior);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
